﻿#if NET45_OR_GREATER
using System;

using Newtonsoft.Json;

using zijian666;
using zijian666.Core;
using zijian666.ConvertExtensions;

namespace zijian666.Json;

/// <summary>
/// 替换默认json转换器
/// </summary>
/// <typeparam name="T"></typeparam>
internal class JsonValueConverter<T> : JsonConverter<T>
{
    public override bool CanRead => true;

    public override bool CanWrite => true;

    public override void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer)
    {
        var result = (ConvertContext.Current?.Convert<string>(value)) ?? value.Convert<string>();
        if (result.Success == true)
        {
            serializer.Serialize(writer, result.Value);
        }
        else
        {
            serializer.Serialize(writer, value);
        }
    }

    public override T? ReadJson(JsonReader reader, Type type, T? existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        var value = serializer.Deserialize(reader);

        var result = (ConvertContext.Current?.Convert(type, value)) ?? value.Convert(type);
        return (T?)result.Value;
    }
}

#endif